package com.xia.gulimall.product.exception;

import com.xia.common.exception.BizCodeEnum;
import com.xia.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author yong.xia
 * @version 1.0
 * @ClassName GulimallExceptionControllerAdvice
 * @description
 * @date 2021/11/4 13:52
 * @since JDK 1.8
 */

@Slf4j
@RestControllerAdvice(basePackages = "com.xia.gulimall.product")
public class GulimallExceptionControllerAdvice {
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e) {
        log.error("数据校验出现问题{},异常类型{}", e.getMessage(), e.getClass());
        BindingResult bindingResult = e.getBindingResult();
        Map<Object, Object> map = new HashMap<>();
        bindingResult.getFieldErrors().stream().forEach(fileds -> {
            String message = fileds.getDefaultMessage();
            String filed = fileds.getField();
            map.put(message, filed);
        });
        return R.error(BizCodeEnum.VAIILD_EXCEPTION.getCode(), BizCodeEnum.VAIILD_EXCEPTION.getMsg()).put("data", map);
    }

    @ExceptionHandler(value = Throwable.class)
    public R handlerException(Throwable throwable) {
        return R.error(BizCodeEnum.UKNOW_EXCEPTION.getCode(), BizCodeEnum.UKNOW_EXCEPTION.getMsg());
    }


}
